﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Infrastructure;

namespace PMS.Web.Framework.Controllers
{
    /// <summary>
    /// Top Controller must be inherited from Base*Controllers
    /// </summary>
    public class PMSController : Controller
    {
        /// <summary>
        /// Creates an object that serializes the specified object to JSON.
        /// </summary>
        /// <param name="data">The object to serialize.</param>
        /// <returns>The created object that serializes the specified data to JSON format for the response.</returns>
        public override JsonResult Json(object data)
        {
            var serializerSettings = EngineContext.Current.Resolve<IOptions<MvcNewtonsoftJsonOptions>>()?.Value?.SerializerSettings
                                   ?? new JsonSerializerSettings();
                
            //API调用时JSON配置序列化时时间格式为时间戳，前端JS需要对格式化时间戳进行Date转化
            serializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
            serializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;

            return base.Json(data, serializerSettings);
        }

        #region Ajax Response for HttpPost

        protected virtual IActionResult SuccessJson(string message)
        {
            return Json(new { state = RespondNotifyType.Success, message });
        }
        protected virtual IActionResult SuccessJson(string message, object data, bool lowerPropName = false)
        {
            if(!lowerPropName)
                return Json(new { state = RespondNotifyType.Success, message, data });
            else
            {
               if(data != null)
               {
                    var serializerSettings = new JsonSerializerSettings();
                    serializerSettings.ContractResolver = new LowercaseContractResolver();
                    var jsonStr = JsonConvert.SerializeObject(data, Formatting.Indented, serializerSettings);
                    return Json(new { state = RespondNotifyType.Success, message, data = jsonStr });
               }
               return Json(new { state = RespondNotifyType.Success, message, data });
            }
        }
        protected virtual IActionResult WarnJson(string message)
        {
            return Json(new { state = RespondNotifyType.Warning, message });
        }
        protected virtual IActionResult ErrorJson(string message)
        {
            return Json(new { state = RespondNotifyType.Error, message });
        }
        #endregion
    }
}
